from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from . import serializer
from . import models
from .pagination import PageNumberPagination
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters.rest_framework import DjangoFilterBackend


# Create your views here.


class CourseCategoryView(GenericViewSet, ListModelMixin):
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).order_by("orders")
    serializer_class = serializer.CourseCategorySerializer


# 课程群查接口
class CourseView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by("orders")
    serializer_class = serializer.CourseModelSerializer
    pagination_class = PageNumberPagination
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    ordering_fields = ["id", "price", "students"]
    filter_fields = ["course_category"]


# 一个课程的所有章节（群查）
class ChapterViewSet(GenericViewSet, ListModelMixin):
    queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializer.CourseChapterSerializer

    # 基于课程分类条件下的查询
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']


# 搜索课程接口
class SearchCourseViewSet(GenericViewSet, ListModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).all()
    serializer_class = serializer.CourseModelSerializer

    pagination_class = PageNumberPagination

    filter_backends = [SearchFilter]
    search_fields = ['name']